package com.shxy.web;

import com.shxy.pojo.Material;
import com.shxy.pojo.MaterialCategory;
import com.shxy.service.ICategoryService;
import com.shxy.service.IMaterialService;
import com.shxy.web.ui.MaterialItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 资源管理控制器
 */
@RestController
@RequestMapping("/material")
public class MaterialController {
    @Autowired
    private IMaterialService materialService;
    @Autowired
    private ICategoryService categoryService;

    /**
     * 资源上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public String fileUpload(MultipartFile file){
        Material material = materialService.uploadFile(file);
        return material.getId();
    }

    /**
     * 资源分类
     * @param materialId
     * @param nodeId
     * @param title
     * @param index
     * @return
     */
    public String materialCategory(String materialId, int nodeId, String title, int index){
        MaterialCategory materialCategory = categoryService.addMaterialCategory(materialId, nodeId, title, index);
        return materialCategory.getId();
    }

    /**
     * 资源搜索
     * @param name
     * @param mtype
     * @return
     */
    public List<MaterialItem> searchMaterials(String name, String mtype){
        List<Material> materials = materialService.search(name, mtype);
        return convertMaterialItems(materials);
    }

    /**
     * 资源转换
     * @param materials
     * @return
     */
    private List<MaterialItem> convertMaterialItems(List<Material> materials) {
        List<MaterialItem> items = new ArrayList<>();
        for (Material m: materials) {
            MaterialItem item = new MaterialItem();
            item.setId(m.getId());
            item.setName(m.getName());
            item.setMType(m.getMType());
            items.add(item);
        }
        return items;
    }
}
